package com.mentalhealthplatform.global.rbac.controller;

import com.mentalhealthplatform.global.rbac.dto.normal.EndpointDTO;
import com.mentalhealthplatform.global.rbac.dto.normal.SimpleEndpointDTO;
import com.mentalhealthplatform.global.rbac.model.Endpoint;
import com.mentalhealthplatform.global.debounce.Debounce;
import com.mentalhealthplatform.global.rbac.model.Permission;
import com.mentalhealthplatform.global.rbac.service.entity.EndpointService;
import com.mentalhealthplatform.global.rbac.service.entity.PermissionService;
import com.mentalhealthplatform.utils.ExportUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/endpoints")
public class EndpointController {

    @Autowired
    private EndpointService endpointService;
    @Autowired
    private PermissionService permissionService;

    @GetMapping("/search")
    @Debounce
    public Page<EndpointDTO> searchEndpoints(
            @RequestParam(required = false, defaultValue = "") String search,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {

        Pageable pageable = PageRequest.of(page - 1, pageSize);
        return endpointService.searchEndpoints(search, pageable);
    }

    @GetMapping("/search-simple")
    @Debounce
    public Page<SimpleEndpointDTO> searchSimpleEndpoints(
            @RequestParam(required = false, defaultValue = "") String search,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {

        Pageable pageable = PageRequest.of(page - 1, pageSize);
        return endpointService.searchSimpleEndpoints(search, pageable);
    }

    @PutMapping("/{id}/status")
    @Debounce
    public ResponseEntity<String> toggleStatus(@PathVariable Long id) {
        try {
            endpointService.toggleEndpointStatus(id);
            return ResponseEntity.ok("接口状态更新成功");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("更新接口状态失败: " + e.getMessage());
        }
    }

    @PutMapping("/{id}/anonymous")
    @Debounce
    public Endpoint toggleAllowAnonymous(@PathVariable Long id) {
        return endpointService.toggleAllowAnonymous(id);
    }

    @GetMapping("/permissions")
    @Debounce
    public ResponseEntity<List<Permission>> getAllPermissions() {
        try {
            List<Permission> permissions = permissionService.getAllPermissions();
            return ResponseEntity.ok(permissions);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @PostMapping
    public ResponseEntity<EndpointDTO> addEndpoint(@RequestBody  EndpointDTO endpointDTO) throws Exception {
        EndpointDTO newEndpointDTO = endpointService.addEndpoint(endpointDTO);
        return ResponseEntity.status(HttpStatus.CREATED).body(newEndpointDTO);
    }

    @PutMapping("/{id}")
    public ResponseEntity<EndpointDTO> updateEndpoint(@PathVariable Long id, @RequestBody EndpointDTO endpointDTO) {
        try {
            EndpointDTO updatedEndpointDTO = endpointService.updateEndpoint(id, endpointDTO);
            return ResponseEntity.ok(updatedEndpointDTO);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteEndpoint(@PathVariable Long id) {
        try {
            endpointService.deleteEndpoint(id);
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }

    @PostMapping("/delete")
    public ResponseEntity<Void> batchDeleteEndpoints(@RequestBody List<Long> ids) {
        try {
            endpointService.batchDeleteEndpoints(ids);
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }

    @PostMapping("/{endpointId}/permissions")
    public ResponseEntity<Void> assignPermissionsToEndpoint(@PathVariable Long endpointId, @RequestBody List<Long> permissionIds) {
        try {
            endpointService.assignPermissionsToEndpoint(endpointId, permissionIds);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }

    @DeleteMapping("/{endpointId}/permissions")
    public ResponseEntity<Void> removePermissionsFromEndpoint(@PathVariable Long endpointId, @RequestBody List<Long> permissionIds) {
        try {
            endpointService.removePermissionsFromEndpoint(endpointId, permissionIds);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }


    // 导出所有接口信息
    @GetMapping("/export/all")
    public void exportEndpoints(HttpServletResponse response) throws IOException {
        // 获取接口数据
        List<EndpointDTO> endpointsToExport = endpointService.getAllEndpoints();

        // 调用工具类导出
        ExportUtils.exportToExcel(response, endpointsToExport, "接口信息", EndpointDTO.class, "接口信息");
    }


    // 导出指定接口信息
    @GetMapping("/export")
    public void exportEndpoints(HttpServletResponse response,
                                @RequestParam(required = false) List<Long> ids) throws IOException {
        // 获取指定接口信息
        List<EndpointDTO> endpointsToExport = (ids != null && !ids.isEmpty())
                ? endpointService.getEndpointsByIds(ids)
                : endpointService.getAllEndpoints();  // 若无指定 ID，导出所有接口

        // 使用工具类导出数据
        ExportUtils.exportToExcel(response, endpointsToExport, "接口信息", EndpointDTO.class, "接口信息");
    }
}
